package dm1101.demo02;

import java.util.Arrays;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ln
 * @version 终极版
 * @date 2022/11/1 15:34
 */
public class MenuLock {
    private static String [] arr=new String[2];
    private static int index=0;
    private static Object lock=new Object();
    public static void main(String[] args) {
        //创建手动锁
        ReentrantLock lock1 = new ReentrantLock();

        Thread thread= new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //上锁
                    lock1.lock();
                    if (arr[index]==null){
                        arr[index]="蓝月亮";
                        index++;
                    }
                }
                finally {
                    lock1.unlock();
                }
            }
        });


        Thread thread1= new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    lock1.lock();
                    if (arr[index]==null){
                        arr[index]="你值得拥有";
                        index++;
                    }
                }
                finally {
                    lock1.unlock();
                }

            }
        });

        thread.start();
        thread1.start();

        try {
            thread.join();
            thread1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Arrays.toString(arr));
    }
}

